package com.zmn.oms.api.controller.third.zhimi;


import com.alibaba.fastjson.JSON;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.office.ExcelUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.third.base.dto.api.ApiInvokResult;
import com.zmn.oms.third.zhimi.ZhimiConsts;
import com.zmn.oms.third.zhimi.api.ZhimiOrderResp;
import com.zmn.oms.third.zhimi.entity.ZhimiOrderExtend;
import com.zmn.oms.third.zhimi.service.ZhimiOrderExtendService;
import com.zmn.oms.third.zhimi.service.ZhimiOrderNotifyService;
import com.zmn.oms.third.zhimi.service.ZhimiOrderService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;


/**
 * @author 孙令福
 * @2020/04/25 17:08
 * description: 智米渠道APP端controller
 */
@RestController
@RequestMapping("/zhimi")
@Slf4j
@Api(value = "智米H5接口", tags={"智米H5接口"})
public class ZhimiH5Controller {

    @Autowired
    private ZhimiOrderService zhimiOrderService;
    @Autowired
    private ZhimiOrderExtendService zhimiOrderExtendService;
    @Autowired
    private ZhimiOrderNotifyService zhimiOrderNotifyService;
    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;


    /**
     * 手动触发：测试同步订单完成接口
     */
    @GetMapping("/syncComplete")
    @ResponseBody
    public ApiInvokResult testSyncComplete(String sign, String orderId) {
        if ("zmnTest666666".equals(sign)) {
            log.info("【智米H5接口】收到手动同步订单请求：orderId=[{}]", orderId);
            ApiInvokResult apiInvokResult = zhimiOrderNotifyService.notifyOrderComplete(Long.parseLong(orderId));
            return apiInvokResult;
        }

        return ApiInvokResult.fail("Who are you???");
    }

    /**
     * 手动触发：拉取一次智米订单数据
     */
    @GetMapping("/getOrder")
    @ResponseBody
    public String doPullOrders(String sign, Integer serviceType) {
        if ("zmnTest666666".equals(sign)) {
            if (!ZhimiConsts.isServiceTypeUseable(serviceType)) {
                return "无效的服务类型参数";
            }

            try {
                zhimiOrderService.pullOrderOne(serviceType);
            } catch (OmsBaseException e) {
                return e.getMessage();
            }
            return "执行成功";
        }
        else {
            return "Who are you???";
        }
    }

    /**
     * 手动触发：拉取一次智米订单数据
     */
    @PostMapping("/addOrder")
    @ResponseBody
    public String doAddOrders(String sign, String data) {
        if ("zmnTest666666".equals(sign)) {
            String str = data;
            ZhimiOrderResp zhimiOrderResp = JSON.parseObject(str, ZhimiOrderResp.class);

            zhimiOrderResp.setMetadata(str);

            zhimiOrderService.testAddOrderOne(zhimiOrderResp);
            return "执行成功";
        }
        else {
            return "Who are you???";
        }
    }

    /**
     * 手动触发：拉取一次智米订单申请的配件物流信息数据
     */
    @GetMapping("/pullExpressByOrderId")
    @ResponseBody
    public ApiInvokResult doPullAppliedPartExpressByOrderId(String sign, String orderId) {
        if ("zmnTest666666".equals(sign) && StringUtil.isNotBlank(orderId)) {
            log.info("【智米H5接口】收到手动拉取配件物流信息请求：orderId=[{}]", orderId);
            ApiInvokResult apiInvokResult = zhimiOrderService.pullAppliedPartExpressByOrderId(Long.parseLong(orderId));
            return apiInvokResult;
        }

        return ApiInvokResult.fail("Who are you???");
    }

    /**
     * 手动触发：更新本地存储的智米的基础字典数据-故障选项
     */
    @GetMapping("/refreshFaults")
    @ResponseBody
    public String refreshZhimiFaults(String sign) {
        if ("0e39fd66fa4b4b239a1c240815103dbf".equals(sign)) {
            ResultDTO resultDTO = zhimiOrderExtendService.refreshZhimiFaults();
            return resultDTO.getMessage();
        }
        else {
            return "Who are you???";
        }
    }

    /**
     * 手动触发：更新本地存储的智米的基础字典数据-配件选项
     */
    @GetMapping("/refreshFaultParts")
    @ResponseBody
    public String refreshZhimiFaultParts(String sign) {
        if ("0e39fd66fa4b4b239a1c240815103dbf".equals(sign)) {
            ResultDTO resultDTO = zhimiOrderExtendService.refreshZhimiFaultParts();
            return resultDTO.getMessage();
        }
        else {
            return "Who are you???";
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    public String export(String sign, String startDay, String endDay, HttpServletResponse response)
            throws UnsupportedEncodingException {
        if (!"0e39fd66fa4b4b239a1c240815103dbf".equals(sign)) {
            return "Who are you???";
        }

        Date startDate = null;
        if (StringUtil.isNotBlank(startDay)) {
            startDate = DateUtil.parse(startDay, "yyyy-MM-dd");
            if (startDate == null) {
                startDate = DateUtil.parse(startDay, "yyyyMMdd");
            }
        }
        if (startDate == null) {
            return "请提供正确的开始时间";
        }

        Date endDate = null;
        if (StringUtil.isNotBlank(endDay)) {
            endDate = DateUtil.parse(endDay, "yyyy-MM-dd");
            if (endDate == null) {
                endDate = DateUtil.parse(endDay, "yyyyMMdd");
            }
        }

        Date startTime = DateUtil.parse(DateUtil.toString(startDate, "yyyy-MM-dd 00:00:00"), DateUtil.FORMAT_DEFAULT);
        Date endTime = (endDate == null)
                ? DateUtil.addMonth(startTime, 1)
                : DateUtil.parse(DateUtil.toString(endDate, "yyyy-MM-dd 00:00:00"), DateUtil.FORMAT_DEFAULT);

        List<EsOrderWork> esOrderWorkList = null;
        Map<Long, ZhimiOrderExtend> filter = null;

        {// 查询智米订单基本信息
            OrderWorkQuery query = new OrderWorkQuery();
            // 数据权限
            query.setPermit(GlobalConsts.YES);
            query.setPermitCompany(GlobalConsts.NO);
            query.setPermitService(GlobalConsts.NO);
            query.setPermitPlatformOrder(GlobalConsts.NO);
            query.setPermitPlatformServer(GlobalConsts.NO);
            query.setQueryWarning(GlobalConsts.YES);

            query.setPageSize(700);

            List<Integer> channelIds = new LinkedList<>();
            channelIds.add(ZhimiConsts.CHANNEL_ID);
            query.setChannelIdList(channelIds);

            String receiveTime = DateUtil.toString(startTime) +","+ DateUtil.toString(endTime);
            query.setReceiveTime(receiveTime);

            List<EsOrderWork> esOrderWorks = zsOrderWorkQueryBService.exportListOrderWorkByQuery(query);;
            if (esOrderWorks != null && esOrderWorks.size() > 0) {
                if (esOrderWorks.size() >= 700) {
                    return "数据太多，请适当缩小日期间隔！";
                }
                esOrderWorkList = esOrderWorks;
            }

            // 查询智米订单配件信息
            if (esOrderWorkList != null) {
                filter = new HashMap<>(esOrderWorkList.size());
                List<ZhimiOrderExtend> zhimiOrderExtends = zhimiOrderExtendService.listOrdersByCreateTime(startTime, endTime);
                if (zhimiOrderExtends != null && zhimiOrderExtends.size() > 0) {
                    for (ZhimiOrderExtend item : zhimiOrderExtends) {
                        filter.put(item.getOrderId(), item);
                    }
                }
            }
        }



        List<List> datas = new LinkedList<>();
        {
            List<String> heads = new ArrayList<>(14);
            heads.add(0, "工单号");
            heads.add(1, "录单时间");
            heads.add(2, "省份");
            heads.add(3, "城市");
            heads.add(4, "工程师");
            heads.add(5, "工程师电话");
            heads.add(6, "派单时间");
            heads.add(7, "预约时间");
            heads.add(8,"上门时间");
            heads.add(9,"完成时间");
            heads.add(10, "配件名称/数量");
            heads.add(11, "新建邮寄单号");
            heads.add(12, "旧件返厂单号");
            heads.add(13, "SN码");
            datas.add(heads);

            if (esOrderWorkList != null) {
                for (EsOrderWork item : esOrderWorkList) {
                    List<String> row = new ArrayList<>(15);
                    row.add(0, String.valueOf(item.getOrderId()));// 工单号
                    row.add(1, DateUtil.toString(item.getInputTime()));// 录单时间
                    row.add(2, item.getProvinceName());// 省份
                    row.add(3, item.getCityName());// 城市
                    row.add(4, item.getMasterName());// 工程师
                    row.add(5, item.getMasterPhone());// 工程师电话
                    row.add(6, DateUtil.toString(item.getDistributeTime()));// 派单时间
                    row.add(7, DateUtil.toString(item.getDutyTime()));// 预约时间
                    row.add(8, DateUtil.toString(item.getVisitTime()));// 上门时间
                    row.add(9, DateUtil.toString(item.getCompleteTime()));// 完成时间

                    String parts = "";
                    String partExpressCode = "";
                    String returnExpressCode = "";
                    String sn = "";
                    ZhimiOrderExtend zhimiOrderExtend = filter.get(item.getOrderId());
                    if (zhimiOrderExtend != null) {
                        List<ZhimiOrderExtend.Part> partList = zhimiOrderExtend.getParts();
                        if (partList != null && partList.size() > 0) {
                            StringBuilder partsBuilder = new StringBuilder();
                            StringBuilder partsExpressCodesBuilder = new StringBuilder();
                            for (ZhimiOrderExtend.Part zhimiPart : partList) {
                                partsBuilder.append(",")
                                        .append(zhimiPart.getName()).append("*").append(zhimiPart.getNumber());

                                if (StringUtil.isNotBlank(zhimiPart.getExpressCode())) {
                                    partsExpressCodesBuilder.append(",").append(zhimiPart.getExpressCode());
                                }
                            }

                            parts = partsBuilder.substring(1);
                            if (partsExpressCodesBuilder.length() > 0) {
                                partExpressCode = partsExpressCodesBuilder.substring(1);
                            }
                        }

                        ZhimiOrderExtend.ReturnFactoryExpress retFcExpress = zhimiOrderExtend.getReturnFactoryExpress();
                        if (retFcExpress != null && StringUtil.isNotBlank(retFcExpress.getExpressCode())) {
                            returnExpressCode = retFcExpress.getExpressCode();
                        }

                        if (StringUtil.isNotBlank(zhimiOrderExtend.getSn())) {
                            sn = zhimiOrderExtend.getSn();
                        }
                    }

                    row.add(10, parts);// 配件名称/数量
                    row.add(11, partExpressCode);// 新建邮寄单号
                    row.add(12, returnExpressCode);// 旧件返厂单号
                    row.add(13, sn);// SN码

                    datas.add(row);
                }
            }

        }

        String fileName = "智米订单配件导出_" + DateUtil.toString(new Date(), DateUtil.FORMAT_DATETIME2) + ".xlsx";
        fileName = new String(fileName.getBytes(), "ISO8859-1");
        ExcelUtil.export(response, datas, fileName, "sheet1", false);
        return null;
    }

}
